package me.zhengjie.domain;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.dto.Response;
import me.zhengjie.dto.sqlServer.*;
import me.zhengjie.repository.*;
import me.zhengjie.service.StorageService;
import me.zhengjie.util.UniqueCodeUtil;
import me.zhengjie.wcs.WmsToWcs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class InBoundService {

    private final InBoundMissionRepository inBoundMissionRepository;
    private final StorageService storageService;
    private final WmsToWcs wmsToWcs;
    private final TaskResultService taskResultService;
    private final InBoundMissionHistoryRepository inBoundMissionHistoryRepository;


    /**
     * 生成入库任务
     */
    @Transactional
    public Integer creatInBoundMission(String palletCode){
        try {
            InBoundMission inBoundMission = new InBoundMission();
            inBoundMission.setMissionCode(UniqueCodeUtil.createCode());
            inBoundMission.setMissionStatus(1);
            inBoundMission.setPriority(0);
            inBoundMission.setPalletCode(palletCode);
            // String zoneCode = stationCode.substring(0, 1);
            inBoundMission.setSource("AInBound");
            Storage storage = distributeStorage("A");
            if (ObjectUtil.isNull(storage)) {
                log.info("没有可用的储位");
                return 2;
            }
            inBoundMission.setDestination(storage.getStorageCode());
            inBoundMission.setCreateTime(DateTime.now().toTimestamp());
            inBoundMissionRepository.save(inBoundMission);
            // 更新储位信息
            storageService.lockStorage(storage.getId());
            if (ObjectUtil.isNotNull(storage)) {
                return 1;
            }
            // 查找所属库区
            /*Pallet pallet = palletRepository.findPalletByPalletCode(palletCode);
            String layUpStationCode = pallet.getLayUpStationCode();
            ProductionStation station = productionStationRepository.findProductionStationByStationCode(layUpStationCode);
            String zoneCode = station.getZoneCode();
            log.info("查找到的载盘所属库区：{}", zoneCode);*/
            return null;
        } catch (Exception e) {
            log.error("分配储位，保存任务失败，失败原因：{}",e.toString());
            return 3;
        }
    }

    /**
     * 分配储位, 需要根据库区分配
     * @return 分配到的储位
     */
    private Storage distributeStorage(String zoneCode){
        return storageService.findSuitableStorage(zoneCode);
    }

    /**
     * 生成发送到wcs的入库任务
     * @param inBoundMission wms管理的入库任务
     * @return wcs管理的入库任务
     */
    public WmsTask getWmsTask(InBoundMission inBoundMission){
        WmsTask wmsTask = new WmsTask();
        wmsTask.setLogicalAddressType(1);
        wmsTask.setWmsTaskId(inBoundMission.getMissionCode());
        wmsTask.setLpnCode(inBoundMission.getPalletCode());
        wmsTask.setLpnType(1);
        wmsTask.setWcsTaskType(1);
        wmsTask.setAisle(1);
        wmsTask.setFromLocation(inBoundMission.getSource());
        wmsTask.setToLocation(inBoundMission.getDestination());
        wmsTask.setLevel(inBoundMission.getPriority());
        wmsTask.setStatus(inBoundMission.getMissionStatus());
        wmsTask.setCreated(inBoundMission.getCreateTime());
        return wmsTask;
    }

    @Transactional
    public Response sendInBoundTask(InBoundMission inBoundMission){

        WmsTask wmsTask = getWmsTask(inBoundMission);
        updateAfterSendTask(wmsTask);
        return wmsToWcs.sendTask(wmsTask);
    }

    public InBoundMission findNewInBoundMission(){
        return inBoundMissionRepository.findNowInBoundMission();
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateAfterSendTask(WmsTask wmsTask){
        inBoundMissionRepository.updateStatusByMissionCode(String.valueOf(wmsTask.getWmsTaskId()),2);
    }

    @Transactional
    public void deleteInBoundMissionById(Integer id){
        inBoundMissionRepository.deleteById(id);
    }

    /**
     * 重发异常的入库任务
     */
    @Transactional
    public String repeatErrorInBoundMission(){
        // 查找最新的异常任务
        List<InBoundMissionHistory> newNoFinishTimeInBoundMissions = inBoundMissionHistoryRepository.findNewNoFinishTimeInBoundMission();
        if (newNoFinishTimeInBoundMissions.size() == 1){
            InBoundMissionHistory inBoundMissionHistory = newNoFinishTimeInBoundMissions.get(0);
            // 重新构建任务
            WmsTask wmsTask = new WmsTask();
            wmsTask.setLogicalAddressType(1);
            wmsTask.setWmsTaskId(inBoundMissionHistory.getMissionCode());
            wmsTask.setLpnCode(inBoundMissionHistory.getPalletCode());
            wmsTask.setLpnType(1);
            wmsTask.setWcsTaskType(1);
            wmsTask.setAisle(1);
            wmsTask.setFromLocation(inBoundMissionHistory.getSource());
            wmsTask.setToLocation(inBoundMissionHistory.getDestination());
            wmsTask.setLevel(0);
            wmsTask.setStatus(0);
            wmsTask.setCreated(inBoundMissionHistory.getCreateTime());

            // 删除异常的历史任务
            inBoundMissionRepository.deleteInBoundMissionByMissionCode(inBoundMissionHistory.getMissionCode());

            // 重发任务
            Response response = null;
            try {
                response = wmsToWcs.sendTask(wmsTask);
            } catch (Exception e) {
                return "重发失败，错误信息：" + e.toString();
            }
            return "重发成功，wcs回复：" + response.toString();
        }
        return "不满足重发条件";
    }
}
